package model

import (
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	UserID   int64  `gorm:"index;comment:Q号"`
	Username string `gorm:"comment:Q昵称"`
	Coins    int64  `gorm:"default:0;comment:当前金币"`
}

func AddUserData(data *User) {
	mysqlDb.Create(&data)
}

func SetUserCoinsByUserID(userID int64, coins int64, remarks string) int64 {
	var user *User
	AddAccountLogByUserID(userID, coins, remarks)
	db_user := mysqlDb.Where(&User{
		UserID: userID,
	}).First(&user)
	if user.Coins < 0 && coins < 0 {
		return -999
	}
	if db_user.RowsAffected == 0 {
		AddUserData(&User{
			UserID: userID,
			Coins:  coins,
		})
		return coins
	} else {
		user.Coins = user.Coins + coins
		mysqlDb.Save(user)
		return coins
	}
}

func ReSetUserCoinsByUserID(userID int64, coins int64, remarks string) int64 {
	var user *User
	AddAccountLogByUserID(userID, coins, remarks)
	db_user := mysqlDb.Where(&User{
		UserID: userID,
	}).First(&user)
	if db_user.RowsAffected == 0 {
		AddUserData(&User{
			UserID: userID,
			Coins:  coins,
		})
		return coins
	} else {
		user.Coins = coins
		mysqlDb.Save(user)
		return coins
	}
}

func GetUserCoinsByUserID(userID int64) int64 {
	var user *User
	db_user := mysqlDb.Where(&User{
		UserID: userID,
	}).First(&user)
	if db_user.Error != nil {
		return 0
	}
	return user.Coins
}

func GetAllUserID() []User {
	var user []User
	mysqlDb.Select("user_id").Find(&user)
	return user
}
